package com.example.easycharge.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.easycharge.entity.Vehicle;
import com.example.easycharge.error.AttributeNotFoundError;
import com.example.easycharge.error.VehicleNotFoundError;
import com.example.easycharge.notRepEntity.VehicleData;
import com.example.easycharge.repository.VehicleRepository;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Tag(name = "车辆接口组")
@Slf4j
@RestController
@RequestMapping("vehicle")
public class VehicleController {
    @Autowired
    private VehicleRepository vehicleRepository;

    @Operation(description = "新增车辆")
    @PostMapping("")
    public JSONObject addNewVehicle(HttpServletRequest httpServletRequest,
                                    @RequestBody VehicleData vehicleData) {
        // TODO: 2022-03-29 对车辆的信息做检查
        JSONObject returnJson = new JSONObject();
        Vehicle vehicle = new Vehicle(vehicleData);
        // 从request中提取出用户编号
        vehicle.setCustomerId((long) httpServletRequest.getAttribute("customerId"));
        vehicle = vehicleRepository.save(vehicle);
        returnJson.put("message", "新增车辆成功");
        returnJson.put("detail", vehicle);
        return returnJson;
    }

    @Operation(description = "查询当前用户全部车辆")
    @GetMapping("")
    public List<Vehicle> findAllVehicle(HttpServletRequest httpServletRequest) {
        return vehicleRepository.findVehiclesByCustomerId((long) httpServletRequest.getAttribute("customerId"));
    }

    @Operation(description = "查询车辆信息的接口，会做鉴权判断是不是自己的车子")
    @Parameter(description = "需要查询的车辆的编号")
    @GetMapping("/{vehicleId}")
    public Vehicle findVehicleDetail(@PathVariable("vehicleId") long vehicleId) throws VehicleNotFoundError {

        Vehicle vehicle = vehicleRepository.findVehicleByVehicleId(vehicleId);
        // 车辆信息未查询到
        if (vehicle == null) {
            throw new VehicleNotFoundError();
        }
        return vehicle;
    }

    @Operation(description = "车辆信息的修改接口，" +
            "可以修改的信息有【chargePower、DC（是否直流）、vehicleType（车辆类型）、numberPlate（车牌号）】")
    @PutMapping("/setting/{vehicleId}/{changeItem}/{newValue}")
    public JSONObject updateVehicleDetail(@PathVariable("vehicleId") long vehicleId,
                                          @PathVariable("changeItem") String changeItem,
                                          @PathVariable("newValue") String newValue) throws AttributeNotFoundError {
        JSONObject jsonObject = new JSONObject();
        String oldValue;
        Vehicle vehicle = vehicleRepository.findVehicleByVehicleId(vehicleId);
        switch (changeItem) {
            case "chargePower":
                oldValue = vehicle.getChargePower() + "";
                vehicle.setChargePower(Integer.parseInt(newValue));
                break;
            case "DC":
                oldValue = vehicle.isDc() + "";
                vehicle.setDc(Boolean.parseBoolean(newValue));
                break;
            case "vehicleType":
                oldValue = vehicle.getVehicleType();
                vehicle.setVehicleType(newValue);
                break;
            case "numberPlate":
                oldValue = vehicle.getNumberPlate();
                vehicle.setNumberPlate(newValue);
                break;
            case "totalEnergy":
                oldValue = vehicle.getTotalEnergy() + "";
                vehicle.setTotalChargeHour(Integer.parseInt(newValue));
                break;
            default:
                throw new AttributeNotFoundError();
        }
        vehicleRepository.save(vehicle);
        jsonObject.put("message", "车辆" + changeItem + "修改成功");
        jsonObject.put("oldValue", oldValue);
        jsonObject.put("newValue", newValue);
        return jsonObject;
    }

    @Operation(description = "删除车辆接口")
    @Parameter(description = "需要删除的车辆的编号")
    @DeleteMapping("/{vehicleId}")
    public JSONObject deleteVehicle(@PathVariable("vehicleId") long vehicleId) throws VehicleNotFoundError {
        JSONObject jsonObject = new JSONObject();
        int deleteResult = vehicleRepository.deleteByVehicleId(vehicleId);
        if (deleteResult == 0) {
            throw new VehicleNotFoundError();
        }
        jsonObject.put("message", "删除成功");
        return jsonObject;
    }
}
